//配置管理模块
const fs = require('fs')
const path = require('path')
const toml = require('@iarna/toml')

// const CONFIG_PATH = path.join(__dirname, 'configs', 'frpc.toml')
const getConfigPath = frpPath => {
  return path.join(frpPath, 'frpc.toml')
}
function appendProxyToConfig(frpPath, name, proxyData) {
  const config = readConfig(frpPath)
  const keys = Object.keys(config)
  const newConfig = {}

  // 1. 保证 common 始终在最前
  if (config.common) {
    newConfig.common = config.common
  }

  // 2. 添加已有非 common、非 name 的项（保留原有顺序）
  for (const key of keys) {
    if (key !== 'common' && key !== name) {
      newConfig[key] = config[key]
    }
  }

  // 3. 最后添加新项
  newConfig[name] = proxyData

  writeConfig(frpPath, newConfig)
}



function readConfig(frpPath) {
  const configPath = getConfigPath(frpPath)
  const content = fs.readFileSync(configPath, 'utf-8')
  return toml.parse(content)
}

function writeConfig(frpPath, configObj) {
  const tomlContent = toml.stringify(configObj)
  const configPath = getConfigPath(frpPath)
  fs.writeFileSync(configPath, tomlContent, 'utf-8')
}

function exportConfig(frpPath) {
  const configPath = getConfigPath(frpPath)

  if (!fs.existsSync(configPath)) {
    throw new Error(`配置文件不存在：${configPath}`)
  }

  return fs.readFileSync(configPath, 'utf-8')
}


function importConfig(frpPath, content) {
  const obj = toml.parse(content)
  writeConfig(frpPath, obj)
  return obj
}

module.exports = {
  readConfig,
  writeConfig,
  exportConfig,
  importConfig,
  appendProxyToConfig,
}
